﻿using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Runtime.Serialization;
using System;

namespace BizTalkFlow.Model
{
    [DataContract]
    public class ArtefactModel
    {
        public enum DateInterval { Day, Hour, Minute, Month, Second };

        [DataMember]
        public List<ArtefactLink> Links { get; set; }
        [DataMember]
        public List<ArtefactLinkInstance> LinkInstances { get; set; }
        [DataMember]
        public List<Artefact> Artefacts { get; set; }

        public static ArtefactModel Load(int numberOfIntervalInPast, DateInterval intervalType, bool includeArtefacts, bool includeLinkInstances)
        {
            DateTime? startDate = null;
            DateTime? endDate = DateTime.UtcNow;

            if (numberOfIntervalInPast == null)
                throw new ArgumentNullException("numberOfIntervalInPast", "You must set this param");

            //managing interval type
            switch (intervalType)
            {
                case DateInterval.Day:
                    startDate = endDate.Value.AddDays(-numberOfIntervalInPast);
                    break;
                case DateInterval.Hour:
                    startDate = endDate.Value.AddHours(-numberOfIntervalInPast);
                    break;
                case DateInterval.Minute:
                    startDate = endDate.Value.AddMinutes(-numberOfIntervalInPast);
                    break;
                case DateInterval.Month:
                    startDate = endDate.Value.AddMonths(-numberOfIntervalInPast);
                    break;
                case DateInterval.Second:
                    startDate = endDate.Value.AddSeconds(-numberOfIntervalInPast);
                    break;
                default:
                    break;
            }

            return Load(null, startDate, endDate, includeArtefacts, includeLinkInstances);
        }

        public static ArtefactModel Load(Guid serviceInstanceId, bool includeArtefacts, bool includeLinkInstances)
        {
            return Load(serviceInstanceId, null, null, includeArtefacts, includeLinkInstances);
        }

        public static ArtefactModel Load(DateTime startDate, DateTime? endDate, bool includeArtefacts, bool includeLinkInstances)
        {
            return Load(null, startDate, endDate, includeArtefacts, includeLinkInstances);
        }

        private static ArtefactModel Load(Guid? serviceInstanceId, DateTime? startDate, DateTime? endDate, bool includeArtefacts, bool includeLinkInstances)
        {
            var artefactModel = new ArtefactModel();
            artefactModel.Links = new List<ArtefactLink>();
            artefactModel.Artefacts = new List<Artefact>();

            string connectionString = ConfigurationManager.ConnectionStrings["BizTalkDTADb"].ConnectionString;

            using (SqlConnection con = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand("Onatica_GetServiceFlows", con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandTimeout = 10 * 60; // 10 min

                    if (serviceInstanceId != null)
                    {
                        var sqlPrama = new SqlParameter("serviceInstanceId", SqlDbType.UniqueIdentifier);
                        sqlPrama.Value = serviceInstanceId;
                        cmd.Parameters.Add(sqlPrama);
                    }
                    cmd.Parameters.AddWithValue("startDate", startDate);
                    cmd.Parameters.AddWithValue("endDate", endDate);
                    cmd.Parameters.AddWithValue("includeArtefacts", includeArtefacts);
                    cmd.Parameters.AddWithValue("includeLinkInstances", includeLinkInstances);

                    con.Open();

                    var result = cmd.ExecuteReader();
                    while (result.Read())
                    {
                        artefactModel.Links.Add(new ArtefactLink()
                        {
                            FowTemplate = result.GetString(0),
                            FromComponentId = result.GetInt32(1),
                            FromComponentName = result.GetString(2),
                            FromServiceName = result.GetString(3),
                            FromServiceType = result.GetString(4),
                            IsTwoWay = result.GetInt32(5),
                            ToComponentId = result.GetInt32(6),
                            ToComponentName = result.GetString(7),
                            ToServiceName = result.GetString(8),
                            ToServiceType = result.GetString(9),
                            ArtefactCount = result.GetInt32(10)
                        });
                    }

                    if (includeArtefacts)
                    {

                        result.NextResult();
                        while (result.Read())
                        {
                            artefactModel.Artefacts.Add(new Artefact()
                            {

                                Id = result.GetInt32(0),
                                Name = result.GetString(1),
                                Type = result.GetString(2),
                                BizTalkMgmtDbComponentId = result.GetInt32(3),
                                ApplicationId = result.GetInt32(4),
                                ApplicationName = result.GetString(5),
                                TwoWay = result.GetInt32(6)
                            });
                        }
                    }

                    if (includeLinkInstances)
                    {
                        artefactModel.LinkInstances = new List<ArtefactLinkInstance>();

                        result.NextResult();
                        while (result.Read())
                        {
                            artefactModel.LinkInstances.Add(new ArtefactLinkInstance()
                            {
                                FowTemplate = result.GetString(0),
                                FromEventId = result.GetInt64(1),
                                FromMessageInstanceId = result.GetGuid(2),
                                FromServiceInstanceId = result.GetGuid(3),
                                FromStatus = result.GetInt32(4),
                                FromComponentId = result.GetInt32(5),
                                FromComponentName = result.GetString(6),
                                FromServiceName = result.GetString(7),
                                FromServiceType = result.GetString(8),
                                FromActivityId = result.GetGuid(9),
                                FromTimestamp = result.GetDateTime(10),
                                FromIs2Way = result.GetInt32(11),
                                ToEventId = result.GetInt64(12),
                                ToMessageInstanceId = result.GetGuid(13),
                                ToServiceInstanceId = result.GetGuid(14),
                                ToStatus = result.GetInt32(15),
                                ToComponentId = result.GetInt32(16),
                                ToComponentName = result.GetString(17),
                                ToServiceName = result.GetString(18),
                                ToServiceType = result.GetString(19),
                                ToActivityId = result.GetGuid(20),
                                ToTimestamp = result.GetDateTime(21),
                                MessageServiceInstance = result.GetGuid(22),
                                FlowId = result.GetGuid(23),
                                Generation = result.GetInt32(24)
                            });
                        }
                    }

                    con.Close();
                }
            }
            return artefactModel;
        }

    }
}